package com.example.springboot.dao.impl;

import com.example.springboot.dao.EntityDao;
import com.example.springboot.entity.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;


@Repository
public class StudentDaoImpl implements EntityDao<Student> {

	@Autowired
	private JdbcTemplate jdbcTemplate;
	
	@Override
	public Student getEntityById(Integer id) {
		List<Student> list = jdbcTemplate.query("select * from tb_student where id = ?", new Object[]{id}, new BeanPropertyRowMapper(Student.class));
		if(list!=null && list.size()>0){
			return list.get(0);
		}else{
			return null;
		}

	}

	@Override
	public List<Student> getEntityList() {
		List<Student> list = jdbcTemplate.query("select * from tb_student", new Object[]{}, new BeanPropertyRowMapper(Student.class));
		if(list!=null && list.size()>0){
			return list;
		}else{
			return null;
		}

	}

	@Override
	public int add(Student student) {
		return jdbcTemplate.update("insert into tb_student(NAME, AGE, SCORE_SUM,SCORE_AVG) values(?, ?, ?, ?)",
				student.getName(),student.getAge(), student.getScore_sum(),student.getScore_avg());
	}

	@Override
	public int update(Integer id, Student student) {
		return jdbcTemplate.update("UPDATE tb_student SET NAME = ? , AGE = ? , SCORE_SUM = ? , SCORE_AVG = ?  WHERE id = ?",
				student.getName(),student.getAge(),student.getScore_sum(),student.getScore_avg(), id);
	}

	@Override
	public int delete(Integer id) {
		return jdbcTemplate.update("DELETE from tb_student where id = ? ",id);
	}

}
